<!--
* @Description: 企业微信 - 表单
* @Author: DHL
* @Date: 2022-03-30 13:50:53
 * @LastEditors: DHL
 * @LastEditTime: 2023-01-13 17:51:32
-->
<template>
  <tw-drawer
    v-model="visible"
    title="微信企业号配置"
    :loading="loading"
    size="800px"
    @close="handleClose"
  >
    <div class="form-wrapper">
      <el-form ref="dbFormRef" :model="dbForm" :rules="rules" label-width="120px">
        <el-form-item label="企业微信ID" prop="corpId">
          <el-input v-model="dbForm.corpId" clearable placeholder="请输入企业微信ID"></el-input>
        </el-form-item>
      </el-form>

      <div class="btn">
        <el-button type="primary" @click="handleOpenApp('add')">添加应用</el-button>
      </div>

      <div class="apps">
        <template v-for="(item, index) in dbForm.appConfigs">
          <el-card shadow="hover">
            <template #header>
              <span>{{ index + 1 }}.</span>
              <div>
                <el-button type="warning" text @click="handleOpenApp('edit', index)">
                  编辑
                </el-button>
                <el-button type="danger" text @click="handleDeleteApp(item.agentId)">
                  删除
                </el-button>
              </div>
            </template>
            <div>
              <el-form label-width="120px">
                <el-form-item label="AgentId" prop="agentId">
                  {{ item.agentId }}
                </el-form-item>

                <el-form-item label="Secret" prop="secret">
                  {{ item.secret }}
                </el-form-item>

                <el-form-item label="域名" prop="domain">
                  {{ item.domain }}
                </el-form-item>

                <el-form-item label="Token" prop="token">
                  {{ item.token }}
                </el-form-item>

                <el-form-item label="AesKey" prop="aesKey">
                  {{ item.aesKey }}
                </el-form-item>

                <el-form-item label="认证重定向URL" prop="oauth2redirectUri">
                  {{ item.oauth2redirectUri }}
                </el-form-item>

                <el-form-item label="消息URL" prop="messageUrl">
                  {{ item.messageUrl }}
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </template>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClose()">取 消</el-button>
      <el-button type="primary" @click="handleSubmit()"> 提 交 </el-button>
    </template>

    <tw-dialog
      v-model="app.visible"
      :title="app.title"
      :loading="app.loading"
      width="600px"
      height="400px"
      @close="handleCloseApp"
    >
      <el-form ref="appDbFormRef" :model="appForm" :rules="appRules" label-width="120px">
        <el-form-item label="AgentId" prop="agentId">
          <el-input v-model="appForm.agentId" clearable placeholder="请输入AgentId"></el-input>
        </el-form-item>

        <el-form-item label="Secret" prop="secret">
          <el-input v-model="appForm.secret" clearable placeholder="请输入Secret"></el-input>
        </el-form-item>

        <el-form-item label="域名" prop="domain">
          <el-input v-model="appForm.domain" clearable placeholder="请输入域名"></el-input>
        </el-form-item>

        <el-form-item label="Token" prop="Token">
          <el-input v-model="appForm.token" clearable placeholder="请输入Token"></el-input>
        </el-form-item>

        <el-form-item label="AesKey" prop="aesKey">
          <el-input v-model="appForm.aesKey" clearable placeholder="请输入AesKey"></el-input>
        </el-form-item>

        <el-form-item label="认证重定向URL" prop="oauth2redirectUri">
          <el-input
            v-model="appForm.oauth2redirectUri"
            clearable
            placeholder="请输入认证重定向URL"
          ></el-input>
        </el-form-item>

        <el-form-item label="消息URL" prop="messageUrl">
          <el-input v-model="appForm.messageUrl" clearable placeholder="请输入消息URL"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleCloseApp()">取 消</el-button>
        <el-button type="primary" @click="handleSubmitApp()"> 提 交 </el-button>
      </template>
    </tw-dialog>
  </tw-drawer>
</template>

<script lang="ts" setup>
  import { debug } from 'console'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { assign, cloneDeep } from 'lodash-es'
  import { TenantConfigModel } from '/@/api/system/model/tenantConfigModel'
  import {
    apiTenantConfigGetByType,
    apiTenantConfigSave,
    apiTenantConfigUpdateById
  } from '/@/api/system/tenantConfig'
  import { isEmpty, isNotEmpty } from '/@/utils/isUtils'
  import { log } from '/@/utils/log'
  import { arrayRemoveByPropertyValue } from '/@/utils/twUtils'

  const loading = ref(true)

  /**
   * 显示弹框
   */
  const visible = ref(false)

  let configForm: TenantConfigModel = {}

  //////////////////////////////////////////////////
  // 表单
  //////////////////////////////////////////////////

  const dbFormRef = ref()

  const defaultForm = {
    corpId: '', // 企业微信ID
    appConfigs: [] as Array<any>
  }

  let dbForm = reactive(cloneDeep(defaultForm))

  /**
   * 表单验证规则
   */
  const rules = reactive({
    corpId: [
      {
        required: true,
        message: '请输入企业微信ID',
        trigger: 'blur'
      }
    ]
  })

  //////////////////////////////////////////////////
  // 应用APP
  //////////////////////////////////////////////////

  const appDbFormRef = ref()

  const appDefaultForm = {
    agentId: '', // 应用ID
    secret: '', // 秘钥
    token: '', // token
    aesKey: '', // aesKey
    oauth2redirectUri: '', // 认证重定向URL
    messageUrl: '', // 消息URL
    domain: ''
  }

  let appForm = reactive(cloneDeep(appDefaultForm))

  /**
   * 应用表单验证
   */
  const appRules = reactive({
    agentId: [
      {
        required: true,
        message: '请输入AgentId',
        trigger: 'blur'
      }
    ],
    secret: [
      {
        required: true,
        message: '请输入Secret',
        trigger: 'blur'
      }
    ],
    token: [
      {
        required: false,
        message: '请输入Token',
        trigger: 'blur'
      }
    ],
    aesKey: [
      {
        required: false,
        message: '请输入AesKey',
        trigger: 'blur'
      }
    ],
    oauth2redirectUri: [
      {
        required: false,
        message: '请输入认证重定向URL',
        trigger: 'blur'
      }
    ],
    messageUrl: [
      {
        required: false,
        message: '请输入消息URL',
        trigger: 'blur'
      }
    ],
    domain: [
      {
        required: true,
        message: '请输入域名',
        trigger: 'blur'
      }
    ]
  })

  const app = reactive({
    visible: false,
    title: '创建应用',
    loading: false,
    action: 'add',
    index: -1
  })

  /**
   * 打开应用弹框
   * @param action
   */
  function handleOpenApp(action: string, index = -1) {
    app.visible = true
    if (action === 'add') {
      app.action = 'add'
      app.title = '创建应用'
    } else if (action === 'edit') {
      app.action = 'edit'
      app.title = '编辑应用'

      if (index > -1) {
        app.index = index
        assign(appForm, cloneDeep(dbForm.appConfigs[index]))
      }
    }
  }

  /**
   * 关闭应用弹框
   */
  function handleCloseApp() {
    app.visible = false
    appForm = reactive(cloneDeep(appDefaultForm))
  }

  /**
   * 提交应用配置
   */
  function handleSubmitApp() {
    appDbFormRef.value.validate((valid: boolean) => {
      if (valid) {
        let check = true

        for (let i = 0; i < dbForm.appConfigs.length; i++) {
          if (i !== app.index) {
            const item = dbForm.appConfigs[i]
            if (item.agentId === appForm.agentId) {
              ElMessage.warning(`配置项【AgentId】值重复`)
              check = false
              return
            }

            if (item.domain === appForm.domain) {
              ElMessage.warning(`配置项【域名】值重复`)
              check = false
              return
            }
          }
        }

        if (check) {
          if (app.action === 'add') {
            const form = cloneDeep(appForm)
            dbForm.appConfigs.unshift(form)
          } else if (app.action === 'edit') {
            dbForm.appConfigs[app.index] = cloneDeep(appForm)
            app.index = -1
          }

          handleCloseApp()
        } else {
          ElMessage.warning('配置参数重复')
        }
      } else {
        log.warn('应用配置', '表单校验失败')
      }
    })
  }

  /**
   * 删除配置
   * @param agentId
   */
  function handleDeleteApp(agentId: string) {
    ElMessageBox.confirm(`此操作将删除应用配置记录, 是否继续?`, '删除提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        arrayRemoveByPropertyValue(dbForm.appConfigs, 'agentId', agentId)
      })
      .catch(() => {
        ElMessage.info('删除被取消了')
      })
  }
  //////////////////////////////////////////////////
  // 函数
  //////////////////////////////////////////////////

  /**
   * 打开弹框
   */
  function handleOpen() {
    visible.value = true
    handleSearch()
  }

  /**
   * 关闭弹框
   */
  function handleClose() {
    dbForm = reactive(cloneDeep(defaultForm))
    visible.value = false
  }

  /**
   * 查询配置信息
   */
  function handleSearch() {
    loading.value = true
    apiTenantConfigGetByType('WX_CP')
      .then((result) => {
        if (result?.success) {
          configForm = result.data
          if (isNotEmpty(configForm.configJson)) {
            assign(dbForm, JSON.parse(configForm.configJson || ''))
          }
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  /**
   * 提交表单
   */
  function handleSubmit() {
    const config: any = cloneDeep(dbForm)

    const submitParams = {
      id: configForm.id,
      unionId: dbForm.corpId,
      configType: 'WX_CP',
      name: '企业微信',
      configJson: JSON.stringify(dbForm)
    }

    dbFormRef.value.validate((valid: boolean) => {
      if (valid) {
        if (isEmpty(configForm.id)) {
          addFun(submitParams)
        } else {
          editFun(submitParams)
        }
      } else {
        log.warn('微信公众号配置', '表单校验失败')
      }
    })
  }

  /**
   * 新增
   * @param isContinue 是否新增并继续
   */
  function addFun(submitParams) {
    loading.value = true
    apiTenantConfigSave(submitParams)
      .then((result) => {
        if (result?.success) {
          ElMessage.success(result.message)
          handleClose()
        } else {
          ElMessage.error(result?.message)
        }
      })
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
  }

  /**
   * 编辑
   * @returns
   */
  function editFun(submitParams) {
    loading.value = true
    apiTenantConfigUpdateById(submitParams)
      .then((result) => {
        if (result?.success) {
          ElMessage.success(result.message)
          handleClose()
        } else {
          ElMessage.error(result?.message)
        }
      })
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
  }

  //////////////////////////////////////////////////
  // 暴露出去，父组件才可以调用到
  //////////////////////////////////////////////////
  defineExpose({
    handleOpen
  })
</script>

<style scoped lang="scss">
  .form-wrapper {
    padding: 10px;

    .btn {
      text-align: right;
    }

    .apps {
      padding: 10px 0px 20px 20px;

      :deep(.el-card) {
        margin-top: 10px;
        .el-card__header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px 20px;
        }
      }
    }
  }
</style>
